#!/usr/bin/env python3
#
#  A library of functions
#  
#  Copyright 2025 Eko Didik Widianto <didik@live.undip.ac.id>
#  
#  This program is free software; you can redistribute it and/or modify
#  it under the terms of the GNU General Public License as published by
#  the Free Software Foundation; either version 3 of the License, or
#  (at your option) any later version.
#  
#  This program is distributed in the hope that it will be useful,
#  but WITHOUT ANY WARRANTY; without even the implied warranty of
#  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#  GNU General Public License for more details.
#  
#  You should have received a copy of the GNU General Public License
#  along with this program. If not, see <https://www.gnu.org/licenses/>.
#

import json
from datetime import date		# Date information
cur_date = date.today().strftime('%Y-%m-%d')
import pandas as pd			# Pandas dataframe

def open_json_file(f):
	"""	Open JSON file wrapper
	Return:
		df -- Pandas dataframe
	"""
	with open(f, "r") as of:
		fjson = json.load(of)
	
	df = pd.DataFrame(fjson['records'])
	return df

def save_file(df, bname, desc=""):	
	""" Save Pandas dataframe to csv and formatted json files """
	df.to_csv(bname+'.csv', sep=";")
	
	prow = {"description": f"{desc}", 
		"created_at":cur_date,
		"len": len(df.index),
		"records": [x for x in df.to_dict(orient='records')]}
			
	with open(bname + ".json", 'w', encoding='utf-8') as f:
		json.dump(prow, f, ensure_ascii=False, indent=2, default = str)

def save_profile(jprof, pprof, bname, desc=""):	
	""" Save journal and publisher dataframe to csv and formatted json files """
	jdf = pd.DataFrame(jprof)
	pdf = pd.DataFrame(pprof)
	
	jdf.to_csv(bname+'.csv', sep=";")
	pdf.to_csv(bname+'.csv', sep=";", mode='a')
	
	prow = {"description": f"{desc}", 
		"created_at":cur_date,
		"journal": jprof,
		"publisher" : pprof}
			
	with open(bname + ".json", 'w', encoding='utf-8') as f:
		json.dump(prow, f, ensure_ascii=False, indent=2, default = str)

def save_aprofile(prof, bname, src="journal", desc="", show=True, ext=False):	
	""" Save the dataframe to csv and formatted json files """
	df = pd.DataFrame(prof)
	
	df.to_csv(bname+'.csv', sep=";")
	
	prow = {"description": f"{desc}", 
		"created_at":cur_date,
		src: prof}
			
	with open(bname + ".json", 'w', encoding='utf-8') as f:
		json.dump(prow, f, ensure_ascii=False, indent=2, default = str)
		
	if show:
		print(); print(desc)
		if ext:
			print(df.to_string())
		else:
			print(df)
		print()
		
